package com.itbour.service.goods.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.itbour.com.page.JspPage;
import com.itbour.com.page.Page;
import com.itbour.common.util.StringUtils;
import com.itbour.dao.goods.GoodsDao;
import com.itbour.dto.com.AreaInfoDto;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.dto.goods.AttractionsDto;
import com.itbour.dto.goods.GoodsInfoDto;
import com.itbour.dto.goods.PayTypeInfoDto;
import com.itbour.dto.goods.ResortDto;
import com.itbour.dto.goods.ResortPicDto;
import com.itbour.dto.goods.ResourceTypeInfoDto;
import com.itbour.service.goods.GoodsService;
import com.opensymphony.xwork2.ActionContext;


/**
*
* copyright   pirate alliance team 2014
* @author     lunxing
*
*/

public class GoodsServiceImpl implements GoodsService {

	private GoodsDao goodsDao;
	
	
	public String getGoodsResourceTypes(String goodsId){
		String resourceTypes="";
		List<ResourceTypeInfoDto> resourceTypeInfoList = goodsDao.selectGoodsResourceTypeByGoodsId(goodsId);
		for(ResourceTypeInfoDto resourceTypeInfo : resourceTypeInfoList){
			resourceTypes = resourceTypes + resourceTypeInfo.getResource_type_id() +",";
		}
		return resourceTypes;
	}
	//画面の商品情報を登録
	public String saveGoodsInfo(List<GoodsInfoDto> goodsInfoList,String userId,String areaId,String selectedResourceTypes,int payTypeId,String goodsId){
		//商品表
		GoodsInfoDto goodsBaseInfo = new GoodsInfoDto();
		//String goodsIdSeq = CommonHelper.getSequence(Constants.TB_GOODS);
		goodsBaseInfo.setGoods_id(goodsId);//商品Id
		//goodsBaseInfo.setGoods_id(goodsInfoList.get(0).getGoods_id());
		goodsBaseInfo.setArea_id(areaId);
		goodsBaseInfo.setUser_id(userId);
		goodsBaseInfo.setPay_type_id(payTypeId);
     //
		//商品分類ID(0:ガイド商品, 1:資源商品)
		goodsBaseInfo.setGoods_type_id(0);
		goodsBaseInfo.setClick_count(0);
		goodsBaseInfo.setIs_hot(true);
		goodsBaseInfo.setIs_new(true);
		goodsDao.insertGoodsBaseInfo(goodsBaseInfo);

		//商品詳細
		for(GoodsInfoDto goodsLanguageInfo : goodsInfoList){
		//	goodsLanguageInfo.setGoods_id(goodsId);	
			goodsDao.insertGoodsLanguageInfo(goodsLanguageInfo);
		}

		//商品と資源商品分類関連
		if(selectedResourceTypes!=null && !selectedResourceTypes.isEmpty()){
			String resourceTypes[] = selectedResourceTypes.split(",");
			for(String resourceTypeId : resourceTypes){
				if(resourceTypeId!=null && !resourceTypeId.isEmpty()){
					GoodsInfoDto goodsResourceTypeR = new GoodsInfoDto();
			        goodsResourceTypeR.setGoods_id(goodsId);
					goodsResourceTypeR.setResource_type_id(Integer.valueOf(resourceTypeId));
					goodsDao.insertGoodsResourceTypeInfo(goodsResourceTypeR);
				}
			}
		}
		
		
		return null;
	}

	//画面の商品情報を登録
	public void updateGoodsInfo(List<GoodsInfoDto> goodsInfoList,String goodsId,String areaId,String selectedResourceTypes,int payTypeId){
		//商品表
		GoodsInfoDto goodsBaseInfo = new GoodsInfoDto();
		goodsBaseInfo.setGoods_id(goodsId);
		goodsBaseInfo.setArea_id(areaId);
		goodsBaseInfo.setPay_type_id(payTypeId);
		goodsDao.updateGoodsBaseInfo(goodsBaseInfo);

		//商品詳細
		for(GoodsInfoDto goodsLanguageInfo : goodsInfoList){
			//商品情報存在性判定
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("goods_id", goodsLanguageInfo.getGoods_id());
			param.put("language_id", goodsLanguageInfo.getLanguage_id());

			int count = goodsDao.checkGoodsByGoodsIdAndLanguage(param);
			if(count>0){
				//商品情報存在場合、更新する
				goodsDao.updateGoodsLanguageInfo(goodsLanguageInfo);
			}else{
				//商品情報存在しない場合、追加する
				goodsDao.insertGoodsLanguageInfo(goodsLanguageInfo);
			}
		}
		
		
		//商品と資源商品分類関連
		goodsDao.deleteGoodsResourceTypeInfo(goodsId);
		
		if(selectedResourceTypes!=null && !selectedResourceTypes.isEmpty()){
			String resourceTypes[] = selectedResourceTypes.split(",");
			for(String resourceTypeId : resourceTypes){
				if(resourceTypeId!=null && !resourceTypeId.isEmpty()){
					GoodsInfoDto goodsResourceTypeR = new GoodsInfoDto();
					goodsResourceTypeR.setGoods_id(goodsId);
					goodsResourceTypeR.setResource_type_id(Integer.valueOf(resourceTypeId));
					goodsDao.insertGoodsResourceTypeInfo(goodsResourceTypeR);
				}
			}
		}

	}

	//商品登録画面に、選択した商品情報を検索する
	public List<GoodsInfoDto> getGoodsListByGoodsId(String goods_id){
		return goodsDao.selectGoodsListByGoodsId(goods_id);
	}
	/**
	 * @return the goodsDao
	 */
	public GoodsDao getGoodsDao() {
		return goodsDao;
	}

	/**
	 * @param goodsDao the goodsDao to set
	 */
	public void setGoodsDao(GoodsDao goodsDao) {
		this.goodsDao = goodsDao;
	}

	//Home Page画面
	public List<ResortDto> selectHomePageGoods() {
		List<ResortDto> resortList = goodsDao.selectHomePageGoodsPagging(null);
		if(resortList != null){
			for(ResortDto dto : resortList){
				if(dto.getIntroduce() != null && dto.getIntroduce().length() > 50){
					dto.setIntroduce(dto.getIntroduce().substring(0,50) + "...");
				}
			}
		}
		return resortList;
	}
	
	public ResortDto getGoodsDetailById(long id){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", id);
//		List<ResortDto> resortList = goodsDao.selectHomePageGoodsPagging(map);
//		if(resortList != null){
//			for(ResortDto dto : resortList){
//				if(dto.getIntroduce() != null && dto.getIntroduce().length() > 350){
//					dto.setIntroduce(dto.getIntroduce().substring(0,350) + "...");
//				}
//				Map<String,Object> map1 = new HashMap<String,Object>();
//				map1.put("resortId",dto.getId());
//				List<AttractionsDto> attractionsList= goodsDao.selectHomePageGoodsChildren(map1);
//				dto.setAttractionsList(attractionsList);
//				if(attractionsList != null){
//					for(AttractionsDto dto2 : attractionsList){
//						if(dto2.getIntroduce() != null && dto2.getIntroduce().length() > 50){
//							dto2.setIntroduce(dto2.getIntroduce().substring(0,50) + "...");
//						}
//					}
//				}
//			}
//			return resortList.get(0);
//		}
		List<ResortDto> resortList = goodsDao.selectGoodsDetail(map);
		ResortDto resort = null;
		if(resortList != null && resortList.size() > 0){
			resort = resortList.get(0);
			String iconUrl = resort.getIcon();
			resort.setImageUrl(resort.getIcon());
			if(StringUtils.isNotEmpty(iconUrl) && iconUrl.lastIndexOf("/") >= 0){
			resort.setImageName(iconUrl.substring(iconUrl.lastIndexOf("/")+1));
			}
			
			List<Map<String,Object>> resortPicList = goodsDao.selectGoodsDetailOfPicList(map);
			
			List<ResortPicDto> picList = new ArrayList<ResortPicDto>();
			resort.setResortPicList(picList);
			for(int i=0;resortPicList!=null && i<resortPicList.size();i++){
				ResortPicDto dto = new ResortPicDto();
				dto.setId((Long)resortPicList.get(i).get("id"));
				String url = (String)resortPicList.get(i).get("url");
				dto.setImageUrl(url);
				if(StringUtils.isNotEmpty(url) && url.lastIndexOf("/") >= 0){
				dto.setImageName(url.substring(url.lastIndexOf("/")+1));
				}
				picList.add(dto);
			}
			//resort.setResortPicList(resortPicList);
			
			map.put("resortId", id);
			resort.setAttractionsList(goodsDao.selectAttractions(map));
			if(resort.getAttractionsList() !=null){
				for(AttractionsDto dto : resort.getAttractionsList()){
					String soundurl = dto.getSoundurl();
					dto.setSoundFileUrl(soundurl);
					if(StringUtils.isNotEmpty(soundurl)&& soundurl.lastIndexOf("/") >= 0){
						dto.setSoundFileName(soundurl.substring(soundurl.lastIndexOf("/")+1));
					}
				}
			}			
				
		}
		return resort;
	}

	public String saveGoodsInfo(ResortDto resortDto, String id) {
		if (StringUtils.isNotEmpty(id)) {
//			// 景区图片删除
//			goodsDao.deleteRPicInfo(resortDto);
//			// 景点图片删除
//			goodsDao.deleteAImgInfo(resortDto.getId());
//			// 景点删除
//			goodsDao.deleteAttractionsInfo(resortDto.getId());
//			// 景区更新
//			goodsDao.updateResortInfo(resortDto);
			
			// 景点删除
			goodsDao.deleteAttractionsInfo(Long.valueOf(id));
			resortDto.setId(Long.valueOf(id));
			// 景区图片删除
			goodsDao.deleteRPicInfo(resortDto);
			// 景区更新
			resortDto.setLabels(removeBlank(resortDto.getLabels()));
			goodsDao.updateResortInfo(resortDto);

			Map<String, Object> param = new HashMap<String, Object>();
			// 景区图片
			if(resortDto.getResortPicList() != null){
				for (ResortPicDto att : resortDto.getResortPicList()) {
					param.put("r_id", id);
					param.put("name", resortDto.getName());
					param.put("type", "");
					param.put("url", resortDto.getImageUrl());

					param.put("table", "et_resort_pic");
					Long rImgId= goodsDao.selectMaxId(param);
					if(rImgId == null){
						rImgId = 1l;
					}
					
					//param.put("id", rImgId+1);
					att.setId(rImgId+1);
					att.setResortId(Long.valueOf(id));
					goodsDao.insertRPicInfo(att);
				}
			}
						

			// 景点
			if (resortDto.getAttractionsList() != null) {
				for (AttractionsDto att : resortDto.getAttractionsList()) {
					// 景点
					param.put("table", "et_attractions");
					Long aId= goodsDao.selectMaxId(param);
					if(aId == null){
						aId = 0l;
					}
					aId= aId+1;
					att.setId(aId);
					att.setResortId(Long.valueOf(id));
					goodsDao.insertAttractionsInfo(att);

				}
			}

		} else {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("table", "et_resort");
			Long resortId= goodsDao.selectMaxId(param);
			if(resortId == null){
				resortId = 1l;
			}else{
				resortId += 1;
			}
			// 景区
			resortDto.setId(resortId);
			//resortDto.setAreaId(2);
			resortDto.setIcon(resortDto.getImageUrl());
			UserInfoDto user = (UserInfoDto)(ActionContext.getContext().getSession().get("user"));
			resortDto.setUserid(user.getUser_id());
			resortDto.setLabels(removeBlank(resortDto.getLabels()));
			goodsDao.insertResortInfo(resortDto);
			
			
			// 景区图片
			if(resortDto.getResortPicList() != null){
				for (ResortPicDto att : resortDto.getResortPicList()) {
					param.put("r_id", resortId);
					param.put("name", resortDto.getName());
					param.put("type", "");
					param.put("url", resortDto.getImageUrl());

					param.put("table", "et_resort_pic");
					Long rImgId= goodsDao.selectMaxId(param);
					if(rImgId == null){
						rImgId = 1l;
					}
					
					//param.put("id", rImgId+1);
					att.setId(rImgId+1);
					att.setResortId(resortId);
					goodsDao.insertRPicInfo(att);
				}
			}
			

			// 景点
			if (resortDto.getAttractionsList() != null) {
				for (AttractionsDto att : resortDto.getAttractionsList()) {
					// 景点
					param.put("table", "et_attractions");
					Long aId= goodsDao.selectMaxId(param);
					if(aId == null){
						aId = 0l;
					}
					aId= aId+1;
					att.setId(aId);
					att.setResortId(resortId);
					goodsDao.insertAttractionsInfo(att);

//					// 景点图片
//					param.put("table", "a_img");
//					Long aImgId= goodsDao.selectMaxId(param);
//					if(aImgId == null){
//						aImgId = 0l;
//					}
//					Map<String, Object> aImg = new HashMap<String, Object>();
//					aImg.put("a_id", aId);
//					aImg.put("id", aImgId+1);
//					aImg.put("name", att.getName());
//					aImg.put("type", "");
//					aImg.put("url", att.getImageUrl());
//					goodsDao.insertAImgInfo(aImg);
				}
			}
			id=String.valueOf(resortId);
		}
		return id;
	}
	
	private String removeBlank(String input) {
		if (StringUtils.isBlank(input)) {
			return input;
		} else {
			return input.replaceAll(" ", "");
		}
	
	}
	
	/**
	 * @param countKey
	 *            查询该表所有记录行的SQL语句ID
	 * @param sqlKey
	 *            需要查询记录的SQL语句ID
	 * @param param
	 *            传递给查询语句的参数
	 * @param pageNo
	 *            需要查询的实际页
	 * @param pageSize
	 *            每页记录行数
	 * @return page对象
	 */
	public Page pageQuery(Map<String,Object> param, Integer pageNo, Integer pageSize) {
		try {
			Page result = null;
			//selectDataSource(dataSource);
			// 实际起始位置
			int skipResults = JspPage.getStartOfPage(pageNo, pageSize);
			int totalSize = goodsDao.selectCnt(param);
			
			while(totalSize >0 && totalSize <= skipResults){
				skipResults= skipResults - pageSize;
				pageNo = pageNo -1;
			}
			param.put("pageSize", pageSize);
			param.put("skipResults", skipResults);
			List data = goodsDao.selectList(param);

			result = new JspPage(skipResults, totalSize, pageSize, data);
			return result;
		} finally {
			//clearSelectDataSource(dataSource);
		}
	}
	
	public List<Map<String,Object>> selectArea(Map<String,Object> param){
		return goodsDao.selectArea(param);
	}
	
	public void saveArea(AreaInfoDto areaDto){
		Map<String, Object> param = new HashMap<String, Object>();
		
		param.put("name", areaDto.getName());
		param.put("parentid", areaDto.getArea_id());
		param.put("table", "et_area");
		Long rImgId= goodsDao.selectMaxId(param);
		if(rImgId == null){
			rImgId = 0l;
		}
		param.put("id", rImgId+1);
		goodsDao.insertArea(param);
	}
	
	public void goodsVerify(String ids, int state){
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ids", StringUtils.listToSQLString(StringUtils.stringToList(ids)));
		param.put("state", state);
		goodsDao.updateVerify(param);
	}

	public List<Map<String,Object>> selectLabels(Map<String,Object> param){
		return goodsDao.selectLabels(param);
	}
	
	public void deleteGoodsInfo(ResortDto resortDto, String id,String delIds) {
		String[] ids = null;
		if(StringUtils.isNotEmpty(delIds)){
			ids = delIds.split(",");
			
		}else if(StringUtils.isNotEmpty(id)){
			ids = new String[]{id};
		}
		for(String idd : ids){
			if (StringUtils.isNotEmpty(idd)) {				
				// 景点删除
				goodsDao.deleteAttractionsInfo(Long.valueOf(idd));
				resortDto = new ResortDto();
				resortDto.setId(Long.valueOf(idd));
				// 景区图片删除
				goodsDao.deleteRPicInfo(resortDto);
				// 景区删除
				goodsDao.deleteResortInfo(resortDto);
			}
		}

	}
	@Override
	public List<Map<String, Object>> selectAreaOfClassificationChild(
			Map<String, Object> param) {
		// TODO Auto-generated method stub
		return goodsDao.selectAreaOfClassificationChild(param);
	}
	@Override
	public List<Map<String, Object>> selectAreaOfClassificationChild2(
			Map<String, Object> param) {
		// TODO Auto-generated method stub
		return goodsDao.selectAreaOfClassificationChild2(param);
	}
}
